<template>
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="名称" prop="qrcodeName" class="w-280px">
        <el-input v-model="queryParams.qrcodeName" clearable placeholder="请输入名称" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button type="primary" plain @click="openAdd">
          <Icon icon="ep:plus" class="mr-5px" /> 新增渠道活码
        </el-button>
        <!-- <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <!-- 添加 row-key="id" 解决列数据中的 table#header 数据不刷新的问题  -->
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column label="活码" prop="qrUrl">
        <template #default="scope">
          <el-image
            v-if="scope.row.qrUrl"
            :src="scope.row.qrUrl"
            :preview-src-list="[scope.row.qrUrl]"
            style="width: 100px; height: 100px"
            show-progress
            preview-teleported
            lazy
          />
          <div v-else>暂无二维码</div>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="qrcodeName" />
      <el-table-column label="客服人员" prop="userList">
        <template #default="scope">
          <el-space direction="vertical">
            <div v-for="user in scope.row.userList" :key="user.id">
              <el-tag type="primary">{{ user.userName }}</el-tag>
            </div>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="自动打标" prop="tagList">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.autoTag">开启</el-tag>
          <el-tag type="danger" v-else>未开启</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="自动备注" prop="autoRemark">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.autoRemark">开启</el-tag>
          <el-tag type="danger" v-else>未开启</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="自动通过好友" prop="skipVerify">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.skipVerify">开启</el-tag>
          <el-tag type="danger" v-else>未开启</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-space>
            <el-button type="primary" link @click="openDetail(scope.row)">查看</el-button>
            <el-button type="primary" link @click="openEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.qrUrl" type="primary" link @click="downloadQrcode(scope.row)">下载活码</el-button>
            <el-button type="danger" link @click="openDelete(scope.row)">删除</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import * as ChannelQrcodeApi from './api'
import download from '@/utils/download'
import { ElMessageBox } from 'element-plus'

defineOptions({ name: 'ChannelQrcode' })

const { currentRoute, push } = useRouter() // 路由跳转
const loading = ref(true) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(2) // 列表的总页数
const list = ref<ChannelQrcodeApi.ChannelQrcodeVO[]>([]) // 列表的数据
const queryFormRef = ref<FormInstance>() // 搜索的表单
// 表单搜索
const queryParams = ref({
  pageNo: 1, // 页数
  pageSize: 10, // 每页显示数量
  qrcodeName: undefined
})
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ChannelQrcodeApi.getChannelQrcodePage(unref(queryParams))
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.value.pageNo = 1
  await getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.value = {
    pageNo: 1, // 页数
    pageSize: 10, // 每页显示数量
    qrcodeName: undefined
  }
  handleQuery()
}
/** 查看详情 */
const openDetail = (data: any) => {
  push({
    name: 'ChannelQrcodeConfig',
    query: {
      id: data.id,
      type: 'detail'
    }
  })
}
/** 编辑 */
const openEdit = (data: any) => {
  push({
    name: 'ChannelQrcodeConfig',
    query: {
      id: data.id,
      type: 'edit'
    }
  })
}
/** 删除 */
const openDelete = (data: any) => {
  ElMessageBox.confirm('确定删除该渠道活码吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await ChannelQrcodeApi.deleteChannelQrcode(data.id)
    await getList()
  })
}
/** 新增 */
const openAdd = () => {
  push({
    name: 'ChannelQrcodeConfig',
    query: {
      type: 'add'
    }
  })
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    ElMessageBox.confirm('确定导出该渠道活码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 发起导出
      exportLoading.value = true
      const data = await ChannelQrcodeApi.exportChannelQrcodeExcel(unref(queryParams))
      download.excel(data, '渠道活码.xls')
      exportLoading.value = false
    })
  } catch {
    exportLoading.value = false
  } finally {
    exportLoading.value = false
  }
}
/** 下载活码 */
const downloadQrcode = async (data: any) => {
  try {
    // 创建一个canvas来绘制图片
    const img = new Image()
    img.crossOrigin = 'anonymous' // 处理跨域问题
    
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      
      // 设置canvas尺寸
      canvas.width = img.width
      canvas.height = img.height
      
      // 绘制图片到canvas
      ctx?.drawImage(img, 0, 0)
      
      // 将canvas转换为blob并下载
      canvas.toBlob((blob) => {
        if (blob) {
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = data.qrcodeName + '.png'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          URL.revokeObjectURL(url) // 释放内存
        }
      }, 'image/png')
    }
    
    img.onerror = () => {
      // 如果跨域或其他错误，尝试直接下载
      const a = document.createElement('a')
      a.href = data.qrUrl
      a.download = data.qrcodeName + '.png'
      a.target = '_blank'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
    
    img.src = data.qrUrl
  } catch (error) {
    console.error('下载失败:', error)
    // 降级方案：直接打开图片链接
    window.open(data.qrUrl, '_blank')
  }
}
// 监听路由变化更新列表，解决订单保存/更新后，列表不刷新的问题。
watch(
  () => currentRoute.value,
  () => {
    getList()
  }
)

/** 初始化 **/
onMounted(async () => {
  await getList()
})
</script>
